#include "LuaPrec.h"
#include "../Common/Ptr.h"
#include "../Memory/PieceMemPool.h"

LuaObject::LuaObject(CLua* lua)
{
	mLua=lua;
}

LuaObject::LuaObject(const LuaObject& obj)
	:PtrClass(obj)
{
	mLua=obj.mLua;
	obj.mLua->RawGetI(LUA_REGISTRYINDEX,obj.mRef);
	mRef=mLua->Ref(LUA_REGISTRYINDEX);
}

LuaObject::LuaObject(const LuaObject* obj)
{
	mLua=obj->mLua;
	obj->mLua->RawGetI(LUA_REGISTRYINDEX,obj->mRef);
	mRef=mLua->Ref(LUA_REGISTRYINDEX);
}

LuaObject::LuaObject(CLua* lua,const char* fieldname)
{
	mLua=lua;
	mLua->GetGlobal(fieldname);
	mRef=mLua->Ref(LUA_REGISTRYINDEX);
}

LuaObject::~LuaObject()
{
	mLua->UnRef(LUA_REGISTRYINDEX,mRef);
}

bool LuaObject::IterNext(Ptr<LuaObject>& key,Ptr<LuaObject>& val)
{
	CHECKSTACK_BEGIN(mLua,0);
	mLua->RawGetI(LUA_REGISTRYINDEX,mRef);
	if(!mLua->IsTable(-1))
	{
		mLua->StackPop(1);
		return false;
	}
	if(key==0)
		mLua->PushNil();
	else
		mLua->RawGetI(LUA_REGISTRYINDEX,key->mRef);
	bool ret=false;
	if(mLua->IterNext(-2))
	{
		int valref = mLua->Ref(LUA_REGISTRYINDEX);
		LuaObject* valobj = new LuaObject(mLua);
		valobj->mRef=valref;
		val=valobj;

		int keyref = mLua->Ref(LUA_REGISTRYINDEX);
		LuaObject* keyobj = new LuaObject(mLua);
		keyobj->mRef=keyref;
		key=keyobj;
		ret=true;
	}
	mLua->StackPop(1);
	return ret;
}

void* LuaObject::operator new(size_t size)
{
	return GPieceMem.Malloc(size);
}

void LuaObject::operator delete(void* ptr)
{
	GPieceMem.Free(ptr);
}

